package top.shiyiri.threading3;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author Aunean
 * @date 2021/12/29
 */

/*
创建线程的方式四：使用线程池

好处：
1.提高响应速度（减少了创建新线程的时间）
2.降低资源消耗（重复利用线程池中线程，不需要每次都创建）
3.便于线程管理
    corePoolSize：核心池的大小
    maximumPoolSize：最大线程数
    keepAliveTime：线程没有任务时最多保持多长时间后会终止
 */
class NumberThread implements Runnable {

    @Override
    public void run() {
        for (int i = 1; i <= 100; i++) {
            if (i % 2 == 0) {
                System.out.println(Thread.currentThread().getName() + ":" + i);
            }
        }
    }
}

class NumberThread2 implements Runnable {

    @Override
    public void run() {
        for (int i = 1; i <= 100; i++) {
            if (i % 2 != 0) {
                System.out.println(Thread.currentThread().getName() + ":" + i);
            }
        }
    }
}

class NumberThread3 implements Callable<Integer> {

    @Override
    public Integer call() throws Exception {
        for (int i = 1; i <= 100; i++) {
            if (i % 10 == 0) {
                System.out.println(Thread.currentThread().getName() + ":" + i);
            }
        }
        return null;
    }
}

public class ThreadPool {

    public static void main(String[] args) {

        //1.提供指定线程数量的线程池
        ExecutorService service = Executors.newFixedThreadPool(10);
        ThreadPoolExecutor service2 = (ThreadPoolExecutor) service;
//        service2.setCorePoolSize(15);


        System.out.println(service.getClass());
        //2.执行指定的线程的操作。需要提供实现Runnable接口或Callable接口的实现类的对象
        service.execute(new NumberThread());//适合用于Runnable
        service.execute(new NumberThread2());

        service.submit(new NumberThread3());//适合用于Callable

        //3.关闭连接池
        service.shutdown();
    }
}
